package com.cyh;

public class GuardedObject {
    private Object response;
    public Object get() {
        synchronized (this) {
            //等待超时用+++++++++++++++++++++++ 2000为设置的超时时间，可以通过参数传递过来
                long begin = System.currentTimeMillis();
                long passedTime = 0;
            //-----------------
            while (response == null) {
                //等待超时用++++++++++++++++++++++
                if(passedTime >= 2000) {
                    break;
                }
                //--------------------
                try {
                    //this.wait();
                    this.wait(2000 - passedTime); //等待超时采用, 兼容了虚假唤醒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //等待超时用+++++++++++++++++++
                passedTime = System.currentTimeMillis() - begin;
                //---------
            }
            return response;
        }
    }
    public void complete(Object response) {
        synchronized (this) {
            this.response = response;
            this.notifyAll();
        }
    }
}
